﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading;
using System.IO;
using System.Collections;

namespace ZeroCross
{
    public class ClienHandler
    {
        private HttpListenerContext Context = null;
        Thread doChat = null;

        public ClienHandler()
        { 
        }

        public ClienHandler(IPlayer player)
        {
            this.Player = player;
        }

        public IPlayer Player { get; set; }

        public IGameRoom IGameRoom
        {
            get
            {
                throw new System.NotImplementedException();
            }
            set
            {
            }
        }

        public void SetRequest(HttpListenerContext request)
        {
            this.Context = request;
            doChat = new Thread(ParseRequest);
            doChat.Start();
        }

        public void ParseRequest()
        {
            try
            {
                //Получение запроса
                string inputCommand = Context.Request.Url.LocalPath;
                inputCommand = inputCommand.Replace("/", "");

                //Обработка запроса
                string ParsedData = Parser(inputCommand);

                //Отправка ответа
                byte[] msg = System.Text.Encoding.UTF8.GetBytes(ParsedData);
                Context.Response.ContentLength64 = msg.Length;
                using (Stream s = Context.Response.OutputStream)
                {
                    s.Write(msg, 0, msg.Length);
                }
                //Закрытие подключения
                Context.Response.Close();
                Context.Response.Abort();
            }
            catch
            {

            }            
        }

        /// <summary>
        /// Сервисный Парсер сообщения
        /// </summary>
        /// <param name="request">запрос от клиента</param>
        /// <returns>Возвращает ответ на запрос</returns>
        private string Parser(string request)
        {
            Console.WriteLine("Requested: " + request);
            string command = request.Split('^')[0];
            string answer = string.Empty;
            Player.LastOnline = 0;
            switch (command)
            {
                case "Login": answer = LoginRequest();
                    break;
                case "Check": answer = CheckRequest(request);
                    break;
                case "Invite": answer = InviteRequest(request);
                    break;
                case "Answer": answer = AnswerRequest(request);
                    break;
                case "Move": answer = MoveRequest(request);
                    break;
                default: break;
            }
            Console.WriteLine("Answered: " + answer);
            return answer;
        }

        private string LoginRequest()
        {            
            Player.OnlineStatus = "online";
            return GetOnlinePlayers();
        }

        private string CheckRequest(string request)
        {
            string result = string.Empty;
            string[] status = Player.OnlineStatus.Split(' ');

            if (Player.OnlineStatus == "online")
            {              
                 result = GetOnlinePlayers();               
            }
            else if (status.Length == 3) //4 - если статус к примеру "invited by Petro", то 3 слово будет ником инициатора
            {
                result = string.Format("{0}{1}", "Invited^", status[2]);
            }
            else if (Player.OnlineStatus == "Playing")
            {
                result = Player.GameRoom.CheckGameState(request.Split('^')[1]);
            }
            return result;
        }

        private string InviteRequest(string request)
        {
            string result = string.Empty;

            string[] arguments = request.Split('^');
            Player.OnlineStatus = "Inviting";
            IPlayer targetPlayer = null;
            foreach (DictionaryEntry Item in Server.PlayerList)
            {
                targetPlayer = (IPlayer)Item.Key;
                if (arguments[3] == targetPlayer.Nickname && targetPlayer.OnlineStatus == "online")
                {
                    targetPlayer.OnlineStatus = string.Format("{0}{1}{2}", "Invited by ", Player.Nickname,"^Tictactoe");
                    break;
                }
            }
            result = "Declined";
            if (targetPlayer != null)
            {
                int count = 0;
                while (count < 20)
                {
                    if (targetPlayer.OnlineStatus == "Accepted")
                    {
                        if (arguments[4] == "Tictactoe")
                        {
                            IGameRoom Gameroom = new TicTacRoom(Player, targetPlayer);
                            Player.GameRoom = Gameroom;
                            targetPlayer.GameRoom = Gameroom;
                        }
                        else
                        {
                            //тоже Тиктак игра :) - другой нету
                            IGameRoom Gameroom = new TicTacRoom(Player, targetPlayer);
                            Player.GameRoom = Gameroom;
                            targetPlayer.GameRoom = Gameroom;
                        }
                        
                        targetPlayer.OnlineStatus = "Playing";
                        Player.OnlineStatus = "Playing";
                        result = "Accepted";
                        break;
                    }
                    else if (targetPlayer.OnlineStatus == "online")
                    {
                        Player.OnlineStatus = "online";
                        break;
                    }
                    Thread.Sleep(1000);
                    count++;
                }
            }
            return result;
        }

        private string AnswerRequest(string request)
        {
            string[] arguments = request.Split('^');

            if (arguments[2] == "Accept")
            {
                Player.OnlineStatus = "Accepted";
            }
            else
            {
                Player.OnlineStatus = "online";
            }
            return "ok";
        }

        private string MoveRequest(string request)
        {
            return Player.GameRoom.Move(request);
        }

        private string GetOnlinePlayers()
        {
            string result = string.Empty;

            foreach (DictionaryEntry Item in Server.PlayerList)
            {
                IPlayer player = (IPlayer)Item.Key;
                if (this.Player.Nickname != player.Nickname && player.OnlineStatus == "online")
                {
                    if (result.Length > 0)
                    {
                        result += "^" + player.Nickname;
                    }
                    else
                    {
                        result = player.Nickname;
                    }
                }
            }
            if (result.Length == 0)
            {
                result = "No players online";
            }
            return result;
        }

    }
}
